package cn.junki.redissondemo.utils;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * 分布式锁封装
 *
 * @author Junki
 * @date 2023-09-05 10:30:21
 */
@Slf4j
@Component
public class LockUtil {

    private final String REDISSON_LOCK = "redisson_lock:";

    @Resource
    private RedissonClient redissonClient;

    public <R> R lock(String key, Supplier<R> supplier) {
        return this.lock(key, -1, null, supplier);
    }

    public <R> R lock(String key, long leaseTime, TimeUnit unit, Supplier<R> supplier) {
        RLock lock = null;
        try {
            lock = redissonClient.getLock(REDISSON_LOCK + key);
            lock.lock(leaseTime, unit);
            return supplier.get();
        } catch (Exception e) {
            log.error("分布式锁 {} 异常：", key, e);
        } finally {
            if (null != lock && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

}
